import re
from rest_framework import serializers
from users.models import User
from django_redis import get_redis_connection

class RegisterUser(serializers.ModelSerializer):
    password2 = serializers.CharField(label='校验密码', allow_null=False, required=True,write_only=True)

    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6, required=True, allow_blank=False, write_only=True)

    allow = serializers.CharField(label='是否同意协议', allow_null=False,required=True,write_only=True)

    token = serializers.CharField(label='登录状态token', read_only=True)  # 增加token字段

    class Meta:
        model = User
        fields = ['username','mobile','password','password2','sms_code','allow','token']

    def validate_mobile(self, value):
        if not re.match(r'1[3-9]\d{9}',value):
            raise serializers.ValidationError('手机号不符合规则')
        return value

    def validated_allow(self,value):
        if value != True:
            raise serializers.ValidationError('必须同意协议')

    def validate(self, attrs):
        password = attrs['password']
        password2 = attrs['password']
        if password != password2:
            raise serializers.ValidationError('前后密码不一致')
        mobile = attrs['mobile']
        sms_code = attrs['sms_code']

        redis_coon = get_redis_connection('code')
        redis_code = redis_coon.get('sms_'+mobile)

        if redis_code is None:
            raise serializers.ValidationError('验证码已过期')
        redis_code = redis_code.decode()

        if redis_code != sms_code:
            raise  serializers.ValidationError('验证码输入错误')
        return attrs
    def create(self, validated_data):

        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        user = super().create(validated_data)

        user.set_password(validated_data['password'])
        user.save()
        from rest_framework_jwt.settings import api_settings
        # 补充生成记录登录状态的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        return user